﻿using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace DServer;

public partial class MainWindow
{
    
    /**
     *  简化集合初始化
     */
    private ObservableCollection<LogEntry> LogEntries { get; } = [];
    
    /**
     *    修复IDE0028：简化集合初始化
     */
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        // 初始化日志
        InitializeLog();
        // 设置事件处理器
        SetupEventHandlers();
    }
    
    /**
     *  初始化日志
     */
    private void InitializeLog()
    {
        // 添加初始日志信息
        AddLog("Control Panel Version: 2.2.1", true);
        AddLog("DServer Version: 2.0.9.0", true);
        AddLog("Windows Version: " + Environment.OSVersion.VersionString, true);
        AddLog($"DServer Directory: {AppDomain.CurrentDomain.BaseDirectory}", true);
        AddLog("Checking for applications", true);
        AddLog("DServer ready to go!", true);
    }

    private void SetupEventHandlers()
    {
        // 为每个服务设置事件处理器
        SetupServiceButtons("Nginx");
        SetupServiceButtons("MySQL");
        SetupServiceButtons("PHP");
        SetupServiceButtons("Redis");

        // 设置功能按钮
        BtnStartAll.Click += (_, _) => AddLog("Starting all services...");
        BtnStopAll.Click += (_, _) => AddLog("Stopping all services...");
        BtnOpenMySql.Click += (_, _) => AddLog("Opening MySQL shell...");
        BtnOpenDirector.Click += (_, _) => AddLog("Opening Wnmp directory...");

        // 设置菜单项事件
        MenuFile.Click += (_, _) => AddLog("File menu selected");
        MenuTools.Click += (_, _) => AddLog("Tools menu selected");
        MenuHelp.Click += (_, _) => AddLog("Help menu selected");
        MenuSiteList.Click += (_, _) => AddLog("localhost menu selected");

        // 添加Help子菜单事件处理
        MenuCheckUpdates.Click += (_, _) => CheckForUpdates();
        MenuAbout.Click += (_, _) => ShowAboutDialog();
    }

    private void CheckForUpdates()
    {
        AddLog("Checking for updates...", true);

        // 实际更新检查逻辑（示例）
        try
        {
            // 这里可以添加实际的更新检查逻辑
            // 例如：从服务器获取最新版本信息
            AddLog("Current version: 2.2.1", true);
            AddLog("Latest version: 2.3.0 available", true);
            AddLog("Visit https://wnmp.x64architecture.com to download", true);
        }
        catch (Exception ex)
        {
            AddLog($"Update check failed: {ex.Message}", true);
        }
    }

    private void ShowAboutDialog()
    {
        AddLog("Showing about dialog", true);
        var aboutDialog = new AboutDialog
        {
            Owner = this,
            WindowStartupLocation = WindowStartupLocation.CenterOwner
        };
        aboutDialog.ShowDialog();
    }

    private void SetupServiceButtons(string serviceName)
    {
        var serviceButtons = new[]
        {
            $"{serviceName}Start",
            $"{serviceName}Stop",
            $"{serviceName}Reload",
            $"{serviceName}Config",
            $"{serviceName}Logs"
        };

        foreach (var buttonName in serviceButtons)
            if (FindName(buttonName) is Button button)
                button.Click += (_, _) => AddLog($"{button.Content} command for {serviceName}");
    }

    /// <summary>
    ///     添加日志条目（新条目添加到顶部）
    /// </summary>
    /// <param name="message">日志消息</param>
    /// <param name="isSystem">是否是系统日志（灰色）</param>
    private void AddLog(string message, bool isSystem = false)
    {
        var timestamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        var logEntry = new LogEntry
        {
            Timestamp = timestamp,
            Message = message,
            IsSystem = isSystem
        };

        // 在UI线程上添加日志（倒序显示）
        Dispatcher.Invoke(() => LogEntries.Insert(0, logEntry));

        // 同时在调试输出中打印
        Debug.WriteLine($"{timestamp} [Log] {message}");
    }
}

/// <summary>
///     日志条目类
/// </summary>
public class LogEntry
{
    public required string Timestamp { get; set; }

    public required string Message { get; set; }

    public bool IsSystem { get; init; }

    // 不同日志类型的文本颜色
    public Brush TextColor => IsSystem ? Brushes.Gray : Brushes.Black;
}